<?php
// 接口-客户管理其他
namespace interface\v1;

use verify;

class clientOtherAppClass extends index
{
	private const title       = '公客池';
	private const page        = 'clientPool';
	private const table       = 'kehu';
	private const tableStaff  = 'kehu_staff';
	private const tablePool   = 'pool';
	private const defaultPool = 'defaultClientPool';//默认客户池ID
	
	/**
	 * 公客池列表
	 *
	 * @return void
	 */
	public function list()
	{
		//公私客
		$where = " a.poolId = b.id and a.manager = '' and a.data_source = 0";
		if (!$this->power(self::page, 'seeAll')) {
			$where .= " and if(b.isSee=1,(b.manager='" . self::$stid . "' or b.collaborator like '" . self::$stid . "'), b.manager='" . self::$stid . "')";
		}
		// 关键字搜索
		if ($this->post('wd')) {
			$wd    = $this->post('wd');
			$where .= " AND (companyName like '%$wd%' OR contactName like '%$wd%' OR contactTel like '%$wd%' ) ";
		}
		//获取查询结果
		$where      .= search([
			"="    => [
				'a.workFlow' => $this->post('workFlow'),
				'a.source'   => $this->post('source'),
				"a.poolId"   => $this->post('poolId'),
			],
			'like' => [
				'a.tags' => $this->post('tag'),
			],
		]);
		$orderBy    = $this->post('orderBy') ?: '创建时间降序';
		$orderByArr = $this->orderBy([
			"search"  => $orderBy,
			"default" => "创建时间降序",
			"array"   => [
				"a.lastFollowTime" => ["asc" => "跟进时间升序", "desc" => "跟进时间降序", "site" => 1],
				"a.time"           => ["asc" => "创建时间升序", "desc" => "创建时间降序", "site" => 2],
				"a.updateTime"     => ["asc" => "更新时间升序", "desc" => "更新时间降序", "site" => 3],
			],
		]);
		$page       = $this->page(["table" => self::table . ' as a, `pool` as b ', 'field' => "a.*", "where" => $where, "order" => $orderByArr['orderBy'],]);
		//数据分析
		$data['result'] = [];
		foreach ($page['array'] as $array) {
			$data['result'][] = [
				"khid"        => $array['khid'],
				'companyName' => $array['companyName'],
				'tags'        => self::filterArray(explode(',', $array['tags'])),
				'contactName' => $array['contactName'],
				'contactTel'  => $array['contactTel'],
				"workFlow"    => $array['workFlow'],
				'source'      => $array['source'],
				'time'        => self::formatDate($array['time'], 'Y/m/d'),
			];
		}
		$data['page']    = $page['para'];
		$data['orderBy'] = $orderBy;
		//返回
		$this->code         = 1;
		$this->resp['data'] = $data;
	}
	
	/**
	 * 待办
	 *
	 * @return void
	 */
	function backlog()
	{
		$this->code = 1;
		$act        = $this->post('act');
		$result     = match ($act) {
			default   => $this->page([
				'table' => 'backlog',
				'where' => " stid = '" . self::$stid . "' AND workFlow = '待处理' AND type in ('客户跟进') AND startDay <='" . $this->date . "' ",
				'order' => 'time desc',
			]),
			'message' => $this->page([
				'table' => 'message',
				'where' => " stid = '" . self::$stid . "' AND see = '否' ",
				'order' => 'time desc',
			])
		};
		$res        = [];
		foreach ($result['array'] as $item) {
			$item['time'] = self::formatDate($item['time'], 'm月d日 H:i');
			$res[]        = $item;
		}
		$this->resp['data'] = [
			'result' => $res,
			'page'   => $result['para'],
		];
	}
	
	/**
	 * 数据看板
	 *
	 * @return void
	 */
	public function dataBoard()
	{
		$this->code         = 1;
		$this->resp['data'] = [
			[
				'type'  => '今日新客',
				'total' => self::total([
					'table' => 'kehu',
					'where' => " manager = '" . self::$stid . "' AND to_days(time) = to_days(now()) ",
				]),
			],
			[
				'type'  => '今日跟进',
				'total' => self::total([
					'table' => 'follow',
					'where' => " stid = '" . self::$stid . "' AND target='客户' AND to_days(time) = to_days(now()) ",
				]),
			],
			[
				'type'  => '今日签单',
				'total' => find(['table' => 'sales_contract', 'where' => " salesman = '" . self::$stid . "' and to_days(time) = to_days(now())  ", 'sum' => "money"]),
			],
			[
				'type'  => '本月新线索',
				'total' => floatval(self::total([
					'table' => 'clue',
					'where' => " manager = '" . self::$stid . "' " . self::timeComparison($this->date, 'month', 'time'),
				])),
			],
			[
				'type'  => '本月新客户',
				'total' => self::total([
					'table' => 'kehu',
					'where' => " manager = '" . self::$stid . "'  " . self::timeComparison($this->date, 'month', 'time'),
				]),
			],
			[
				'type'  => '本月新签单',
				'total' => floatval(find(['table' => 'sales_contract', 'where' => " salesman = '" . self::$stid . "'  " . self::timeComparison($this->date, 'month', 'time'), 'sum' => "money"])),
			],
		];
	}
	
	/**
	 * 业绩目标 - 返回数据
	 *
	 * @return void
	 */
	public function salesTarget()
	{
		$month              = date('Y-m');
		$result             = [
			'target' => floatval(find(['table' => 'performance_target', 'where' => "month = '$month' AND stid = '" . self::$stid . "' ", 'sum' => "money"])),
			'real'   => floatval(find([
				'table' => 'sales_contract',
				'where' => "state = '已通过' and date_format(signedDate,'%Y-%m') ='$month' AND stid = '" . self::$stid . "' ", 'sum' => "money",
			])),
		];
		$this->code         = 1;
		$this->resp['data'] = $result;
	}
	
	/**
	 * 销售漏斗 - 返回数据
	 *
	 * @return void
	 */
	public function cluesData()
	{
		$where = '';
		$stid  = $this->post('stid');
		$date  = $this->post('date');
		if (!self::isNull($stid)) {
			$where .= " AND stid = '$stid' ";
		} else {
			$where .= " AND stid = '" . self::$stid . "' ";
		}
		
		if (!self::isNull($date)) {
			$where .= self::timeComparison($date, 'month', 'time');
		} else {
			$where .= self::timeComparison($this->date, 'month', 'time');
		}
		$tableArray = ['线索', '潜在客户', '目标客户', '商机', '成交'];
		$result     = [];
		foreach ($tableArray as $type) {
			$total    = match ($type) {
				'线索'   => self::total([
					'table' => 'clue',
					'where' => $where,
				]),
				'潜在客户' => self::total([
					'table' => 'kehu',
					'where' => " `workFlow` in ('初次联系', '跟进客户')" . $where,
				]),
				'目标客户' => self::total([
					'table' => 'kehu',
					'where' => " `workFlow` ='意向客户' " . $where,
				]),
				'商机'   => self::total([
					'table' => 'opportunity',
					'where' => " `stage` = '已签单' " . $where,
				]),
				'成交'   => self::total([
					'table' => 'sales_contract',
					'where' => " `state` ='已通过' " . $where,
				]),
			};
			$result[] = [
				'name' => $type,
				'data' => $total,
			];
		}
		$this->code         = 1;
		$this->resp['data'] = $result;
	}
	
	/**
	 * 分配客户
	 *
	 * @return void
	 */
	public function transferEdit()
	{
		$listId = $this->post('khid') ? explode(',', $this->post('khid')) : $this->post('listId');
		$field  = array(
			'lastFollowTime' => '',
			'manager'        => $this->post('manager'),
			'collaborator'   => $this->post('collaborator') ?: [],
		);
		if (!$this->power(self::page, 'edit')) {
			$this->resp['warn'] = '您还没有' . self::title . '的编辑权限';
		} elseif (empty($listId) || !is_array($listId)) {
			$this->resp['warn'] = '请选择所需要分配的客户';
		} elseif (empty($field['manager'])) {
			$this->resp['warn'] = '请选择负责人';
		} elseif (is_array($this->post('collaborator')) && in_array($field['manager'], $this->post('collaborator'))) {
			$this->resp['warn'] = '所选的协作人中包含了负责人';
		} else {
			$x = 0;
			//查看范围
			$seeArr                = array_merge([$field['manager']], (is_array($field['collaborator']) ? $field['collaborator'] : explode(',', $field['collaborator'])));
			$field['see']          = implode(',', self::filterArray($seeArr));
			$field['collaborator'] = empty($field['manager']) ? '' : $field['collaborator'];
			$manager               = query('staff', "stid = '$field[manager]'");
			foreach ($listId as $id) {
				$info = query(self::table, " khid = '$id'");
				$pool = query(self::tablePool, "id = '$info[poolId]'");
				if ($pool['manager'] == self::$stid) {
					if ($pool['isCooper']) {
						//设置客户池负责人为协作人
						$field['collaborator'] = array_unique(array_filter(array_merge((is_array($field['collaborator']) ? $field['collaborator'] : explode(',', $field['collaborator'])), [$pool['manager']])));
						$field['see']          = implode(',', array_unique(array_filter(array_merge([$field['manager']], $field['collaborator']))));
						$field['collaborator'] = implode(',', $field['collaborator']);
					}
					$field['disTime'] = $this->time;
					$warn             = static::update([
						'table' => self::table,
						'field' => $field,
						'where' => " khid = '$id'",
					]);
					if ($warn == '更新成功') {
						$x++;
						(new clientAppClass())->logWrite($id, '分配');
						$text = $this->control['name'] . "分配了" . self::title . "【{$info['companyName']}】， id：【" . $id . '】给负责人：' . $manager['name'];
						$this->logText(["type" => self::page, "text" => $text]);
					}
				} else {
					$text = $this->control['name'] . "分配" . self::title . "【{$info['companyName']}】失败：不是负责人";
					$this->logText(["type" => self::page, "text" => $text]);
				}
			}
			$this->code         = ($x === 0) ? 0 : 1;
			$this->resp['warn'] = ($x > 0) ? "成功分配" . $x . '条数据' : '权限不足';
		}
		
		resp:
	}
	
	
	/**
	 * 详情
	 *
	 * @return void
	 */
	public function detail()
	{
		$id   = $this->post('khid');
		$info = query(self::table, " khid = '" . $id . "'");
		if (empty($id)) {
			$this->resp['warn'] = "ID为空";
		} elseif (empty($info['khid'])) {
			$this->resp['warn'] = "未找到此客户信息";
		} else {
			$data           = [];
			$data['info']   = [
				'khid'            => $info['khid'],
				'companyName'     => $info['companyName'],
				'contactTel'      => $info['contactTel'],
				'workFlow'        => $info['workFlow'],
				'time'            => self::formatDate($info['time'], 'm月d日 H:i'),
				'manager'         => self::findStaff($info['manager']),
				'nature'          => $info['nature'],
				'contactIdentity' => $info['contactIdentity'],
				'landline'        => $info['landline'],
				'contactWx'       => $info['contactWx'],
				'contactQQ'       => $info['contactQQ'],
				'website'         => $info['website'],
				'email'           => $info['email'],
				'address'         => $info['address'],
				'birthDay'        => $info['birthDay'],
			];
			$pool           = query(self::tablePool, " id = '{$info['poolId']}' ");
			$data['manage'] = [
				'level'            => $info['level'],
				'classify'         => $info['classify'],
				'industry'         => $info['industry'],
				'scale'            => $info['scale'],
				'source'           => $info['source'],
				'tags'             => self::filterArray(explode(',', $info['tags'])),
				'workFlow'         => $info['workFlow'],
				'followTime'       => $info['followTime'],
				'poolId'           => $info['poolId'],
				'poolName'         => $pool['name'],
				'managerName'      => self::findStaff($info['manager']),
				'manager'          => $info['manager'],
				'collaboratorName' => self::findStaff(explode(',', $info['collaborator'])),
				'collaborator'     => $info['collaborator'],
				'text'             => $info['text'],
			];
			//返回
			$this->code         = 1;
			$this->resp['data'] = $data;
		}
	}
	
	
	/**
	 * 新增客户
	 *
	 * @return void
	 */
	public function editEdit()
	{
		$this->code = 0;
		$id         = $this->post('id') ?: self::getId();
		$labelMxId  = $this->post('tagId') ? explode(',', $this->post('tagId')) : [];//标签ID
		$field      = [
			"contactName"     => $this->post('contactName'),//联系人姓名
			"contactIdentity" => $this->post('contactIdentity'),//联系人身份
			"contactTel"      => $this->post('contactTel'),//联系人手机号码
			"contactQQ"       => $this->post('contactQQ'),//联系人QQ号码
			"contactWx"       => $this->post('contactWx'),//联系人微信号
			"address"         => $this->post('address'),
			"birthDay"        => $this->post('birthDay'),
			"website"         => $this->post('website'),
			"email"           => $this->post('email'),
			"nature"          => $this->post('nature'),
			"invoiceCompany"  => $this->post('invoiceCompany'),
			"postAddress"     => $this->post('postAddress'),
			"workFlow"        => $this->post('workFlow'),//跟进状态
			"source"          => $this->post('source'),//客户来源
			"level"           => $this->post('level'),
			"classify"        => $this->post('classify'),
			"scale"           => $this->post('scale'),
			'followTime'      => $this->post('followTime'),
			"industry"        => $this->post('industry'),//所在行业
			"text"            => $this->post('text'),
			"companyName"     => $this->post('companyName'),//公司名称
			"companyNum"      => $this->post('companyNum'),//纳税人识别号
			"companyBank"     => $this->post('companyBank'),//公司开户银行
			"companyBankNum"  => $this->post('companyBankNum'),//对公账号
			"landline"        => $this->post('landline'),//公司座机
			"companyAddress"  => $this->post('companyAddress'),//开票地址
			'poolId'          => $this->post('poolId') ?: self::defaultPool,
			'manager'         => $this->post('manager'),
			'region'          => '',
			'collaborator'    => $this->post('collaborator') ?: '',
			"updateTime"      => date("Y-m-d H:i:s"),//更新时间
		];
		$annotation = [
			'companyName' => '客户名称',
			'contactName' => '常用联系人',
			'nature'      => '性质',
			"contactTel"  => '手机号码',
			'manager'     => '负责人',
		];
		$rules      = [
			'companyName' => 'required',
			'contactName' => 'required',
			'nature'      => 'required',
			"contactTel"  => 'required|tel',
		];
		// 校验是否符合规则
		$vt     = new verify();
		$result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
		if ($result === false) {
			$this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
			goto resp;
		}
		$where  = " khid = '$id' ";
		$info   = query(self::table, $where);
		$repeat = [
			"khid"  => $id,
			"field" => $field,
			"name"  => ["contactTel" => "联系人手机号码", "contactQQ" => "联系人QQ", "companyName" => "公司名称", "companyNum" => "纳税人识别号"],
		];
		//判断
		if (!$this->power(self::page, "edit")) {
			$this->resp['warn'] = "你没有编辑" . self::title . "的权限";
		} elseif (!empty($field['email']) && preg_match(checkEmail, $field['email']) == 0) {
			$this->resp['warn'] = '邮箱格式错误';
		} elseif (!empty($field['contactQQ']) && preg_match(checkInteger, $field['contactQQ']) == 0) {
			$this->resp['warn'] = 'QQ号码格式错误';
		} elseif (!empty($field['website']) && preg_match(checkUrl, $field['website']) == 0) {
			$this->resp['warn'] = '网址格式错误';
		} elseif (is_array($this->post('collaborator')) && in_array($field['manager'], $this->post('collaborator'))) {
			$this->resp['warn'] = '所选的协作人中包含了负责人';
		} elseif ($warn = clientAppClass::repeat($repeat)) {
			$this->resp['warn'] = $warn;
		} elseif (self::total(['table' => self::table, 'where' => "companyName = '$field[companyName]' and khid !='$id'"]) > 0) {
			$this->resp['warn'] = '已存在此客户名称';
		} else {
			//查看范围
			$field['see'] = implode(',', array_filter(array_unique(array_merge(explode(',', $field['collaborator']), [$field['manager']]))));
			if ($this->post('location')) {
				$location     = explode(',', $this->post('location'));
				$field['lat'] = $location[0];
				$field['lng'] = $location[1];
				$region       = clientAppClass::coordinateToAddr($field['lat'], $field['lng']);
				if ($region['err_code'] == 0) {
					$field['region'] = $region['data']['address_component']['province'] . '-' . $region['data']['address_component']['city'] . '-' . $region['data']['address_component']['district'];
				}
			}
			
			if (!$info['khid']) {
				$userNo             = self::generateCode(self::page,[
                    'prefix' => 'C',
                    'table'  => self::table,
                    'field'  => 'orderNo',
                    'where'  => '',
                ],$field);
				$field              = array_merge($field, [
					'khid'    => $id,
					'orderNo' => $userNo,
					'stid'    => $this->control['stid'],
					'time'    => $this->time,
				]);
				$this->resp['warn'] = static::insert(["table" => self::table, "field" => $field]);
			} else {
				$this->resp['warn'] = static::update([
					"table" => self::table,
					"field" => $field,
					"where" => $where,
				]);
			}
			if (in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
				$tagsText = '';
				//添加标签
				$kehuLabelId = [];
				if (!empty($labelMxId) && is_array($labelMxId)) {
					foreach ($labelMxId as $tagsId) {
						$kehu_label = query('kehu_label', "targetId = '$id' and tag_detail_id = '$tagsId'");
						$tagsDetail = query('tag_detail', "id = '$tagsId'");
						$tags       = query('tag', "id = '$tagsDetail[orderId]'");
						$tagsText   .= $tagsDetail['name'] . ',';
						if (empty($kehu_label['id'])) {
							$mid           = self::getId();
							$kehuLabelId[] = $mid;
							static::insert(array(
								'table' => 'kehu_label',
								'field' => [
									'id'            => $mid,
									'targetId'      => $id,
									'tag_detail_id' => $tagsId,
									'tagId'         => $tags['id'],
									'type'          => 1,
									'time'          => $this->time,
								],
							));
						} else {
							$kehuLabelId[] = $kehu_label['id'];
						}
					}
				}
				//删除无效关联的标签
				delete(['table' => 'kehu_label', 'where' => "id not in ('" . implode("','", $kehuLabelId) . "') and targetId = '$id'"]);
				update(['table' => self::table, 'field' => ['tags' => $tagsText], 'where' => "khid = '$id'"]);
				//常用联系人添加到联系人中
				//添加日志
				$type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
				$text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
				(new clientAppClass())->logWrite($id, $type);
				$this->logText(["type" => self::page, "text" => $text]);
				//返回
				$this->code = 1;
			}
		}
		
		resp:
	}
	
	/**
	 * （抢）获取客户
	 *
	 * @return void
	 */
	public function obtain()
	{
		$id = $this->post('khid');
		//客户
		$info = query(self::table, " khid = '$id'");
		//先判断他是不是此客户池的能查看到的人
		if (empty($info['khid'])) {
			$this->resp['warn'] = '未找到客户';
		} elseif (!empty($info['manager'])) {
			$this->resp['warn'] = '此客户已有负责人了，请去获取其他客户吧';
		} else {
			$pool  = query(self::tablePool, "id = '$info[poolId]'");
			$field = [
				'manager'        => self::$stid,
				'see'            => self::$stid,
				'collaborator'   => '',
				'lastFollowTime' => '',
				'disTime'        => $this->time,
			];
			if ($pool['isCooper']) {
				//设置线索池负责人为协作人
				$field['collaborator'] = array_unique(array_filter(array_merge(explode(',', $field['collaborator']), [$pool['manager']])));
				$field['see']          = implode(',', array_unique(array_filter(array_merge([$field['manager']], $field['collaborator']))));
				$field['collaborator'] = implode(',', $field['collaborator']);
			}
			$warn = update([
				'table' => self::table,
				'field' => $field,
				'where' => " khid = '$info[khid]'",
			]);
			if ($warn == '更新成功') {
				$text = $this->control['name'] . "获取了客户【{$info['companyName']}】， id：【" . $id . '】';
				$this->logText(["type" => self::page, "text" => $text]);
				//日志
				(new clientAppClass())->logWrite($id, '获取', $this->control['name'] . "获取了客户");
				$this->code         = 1;
				$this->resp['warn'] = "获取成功";
			}
		}
	}
	
	/**
	 * 删除公客
	 *
	 * @return void
	 */
	public function delPublicClient(): void
	{
		$array = $this->post('khid') ? explode(',', $this->post('khid')) : '';
		if (!$this->power(self::page, "del")) {
			$this->resp['warn'] = "你没有删除的权限";
		} elseif (empty($array)) {
			$this->resp['warn'] = "你一个数据都没有选择呢";
		} else {
			$text  = "";
			$x     = 0;
			$array = is_array($array) ? $array : [$array];
			foreach ($array as $id) {
				$info   = query(self::table, " khid = '$id' ");
				$result = find(array('table' => 'file', 'where' => "targetId = '$id'"));
				foreach ($result['array'] as $file) {
					fileDelete($file['src']);
				}
				//删除附件
				delete(array("table" => "file", "where" => " targetId = '$id' "));
				//删除标签
				delete(array("table" => "kehu_label", "where" => " targetId = '$id' "));
				//删除跟进记录
				delete(array("table" => "follow", "where" => " targetId = '$id' "));
				//删除操作日志
				delete(array("table" => "clue_log", "where" => " orderId = '$id' "));
				//最后删除基本参数
				delete(array("table" => self::table, "where" => " khid = '$id' "));
				//返回
				$warn = "删除成功";
				$x++;
				$text .= self::title . "ID【" . $info['khid'] . "】" . $warn . "。<br>";
			}
			//添加日志
			$text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
			$this->logText(["type" => self::page, "text" => $text]);
			$this->resp['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
			$this->code         = 1;
		}
	}
	
	/**
	 * 功能清单
	 *
	 * @return void
	 */
	public function func()
	{
		$imgSrc     = root . 'img/miniProgram/crm/';
		$this->code = 1;
		
		$items = [
			'client'     => [
				'name' => '客户',
				'icon' => $imgSrc . 'client.svg',
				'url'  => '/pages/client/client',
			],
			'clientPool' => [
				'name' => '公客池',
				'icon' => $imgSrc . 'publicClient.svg',
				'url'  => '/pages/publicClient/publicClient',
			],
			'kehuStaff'  => [
				'name' => '联系人',
				'icon' => $imgSrc . 'contacts.svg',
				'url'  => '/pages/contacts/contacts',
			],
			"follow"     => [
				'name' => '跟进记录',
				'icon' => $imgSrc . 'follow.svg',
				'url'  => '/pages/follow/follow',
			],
			'visitPlan'  => [
				'name' => '访客计划',
				'icon' => $imgSrc . 'visitPlan.svg',
				'url'  => '/pages/visitPlan/visitPlan',
			],
		];
		$array = [];
		foreach ($items as $page => $item) {
			if ($this->power($page, 'see')) {
				$array[] = $item;
			}
		}
		$this->resp['data'] = [
			[
				'title' => '客户',
				'array' => $array,
			],
		];
	}
	
}